/* eslint-disable */
export default {
  created () {
    const utils = this

    window.UE.plugin.register('simpleupload', function (){
      var me = this,
        isLoaded = true,
        containerBtn;

      function initUploadBtn(){
        var w = containerBtn.offsetWidth || 20,
          h = containerBtn.offsetHeight || 20,
          btnIframe = document.createElement('iframe'),
          btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';

        window.UE.dom.domUtils.on(btnIframe, 'load', function(){

          var timestrap = (+new Date()).toString(36),
            wrapper,
            btnIframeDoc,
            btnIframeBody;

          btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
          btnIframeBody = btnIframeDoc.body;
          wrapper = btnIframeDoc.createElement('div');

          wrapper.innerHTML =
            '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
            'style="' + btnStyle + '">' +
            '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';

          wrapper.className = 'edui-' + me.options.theme;
          wrapper.id = me.ui.id + '_iframeupload';
          btnIframeBody.style.cssText = btnStyle;
          btnIframeBody.style.width = w + 'px';
          btnIframeBody.style.height = h + 'px';
          btnIframeBody.appendChild(wrapper);

          if (btnIframeBody.parentNode) {
            btnIframeBody.parentNode.style.width = w + 'px';
            btnIframeBody.parentNode.style.height = w + 'px';
          }

          var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
          var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
          var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);

          window.UE.dom.domUtils.on(input, 'change', function(e){
            if(!input.value) return;
            var loadingId = 'loading_' + (+new Date()).toString(36);
            var allowFiles = me.getOpt('imageAllowFiles');
            me.focus();
            me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');

            // 判断文件格式是否错误
            var filename = input.value,
              fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
            if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
              showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
              return;
            }

            // 走oss逻辑
            utils.$upload.simple(
              // TODO
              {
                target: { // 过不了ali-oss的校验，要求是File类型
                  files: Array.from(e.target.files).map(item => new File([item], item.name, {type: item.type}))
                }
              },
              {
                subSystem: utils.subSystem,
                fileOwnerType: utils.fileOwnerType
              }
            ).then(file => {
              const loader = me.document.getElementById(loadingId);
              loader.setAttribute('src', file.blob);
              loader.setAttribute('fileuuid', file.fileUuid);
              loader.setAttribute('_src', file.blob);
              loader.setAttribute('title', '');
              loader.removeAttribute('id');
              window.UE.dom.domUtils.removeClasses(loader, 'loadingclass');
            })
          });

          var stateTimer;
          me.addListener('selectionchange', function () {
            clearTimeout(stateTimer);
            stateTimer = setTimeout(function() {
              var state = me.queryCommandState('simpleupload');
              if (state == -1) {
                input.disabled = 'disabled';
              } else {
                input.disabled = false;
              }
            }, 400);
          });
          isLoaded = true;
        });

        btnIframe.style.cssText = btnStyle;
        containerBtn.appendChild(btnIframe);
      }

      return {
        bindEvents:{
          'ready': function() {
            //设置loading的样式
            window.UE.utils.cssRule('loading',
              '.loadingclass{display:inline-block;cursor:default;background: url(\''
              + this.options.themePath
              + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
              '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
              + this.options.themePath
              + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
              '}',
              this.document);
          },
          /* 初始化简单上传按钮 */
          'simpleuploadbtnready': function(type, container) {
            containerBtn = container;
            initUploadBtn()
          }
        },
        outputRule: function(root){
          window.UE.utils.each(root.getNodesByTagName('img'),function(n){
            if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
              n.parentNode.removeChild(n);
            }
          });
        },
        commands: {
          'simpleupload': {
            queryCommandState: function () {
              return isLoaded ? 0:-1;
            }
          }
        }
      }
    });
  }
}
